#!/usr/bin/python
import os
import subprocess
import time
import signal
import re

pVlc = subprocess.Popen("vlc -vvv http://202.120.58.189:3054 --sout '#std{access=file,mux=ts,dst=./tv.ts}'", shell=True, stderr=subprocess.PIPE)
print "VLC started!"

#time.sleep(2)
#pSource = subprocess.Popen("./source tvb.ts tv.ts", shell=True, stdout=subprocess.PIPE)


print "Source ready!"
time.sleep(2)
pIndex = subprocess.Popen("./MPEG2TransportStreamIndexer tv.ts", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print "Creating Index!"
time.sleep(1)
pLive = subprocess.Popen("./live555MediaServer", shell = True, stderr = subprocess.PIPE)
print "Live555 server started!"

indexfile = open("/var/www/html/snapshotindex","w")
start = time.time()
indexfile.write(str(start)+"\n")
pcurtime = subprocess.Popen("./curtime.py",shell=True )
count=0
while True:
	#pLen = subprocess.Popen("mplayer -identify tv.ts -nosound -vc dummy -vo null", shell=True, stderr=subprocess.PIPE,  stdout=subprocess.PIPE)
	#for l in pLen.stdout.readlines():
	#	if re.search("LENGTH",l):
	#		m = re.search(r"\d+",l)
	#		t = m.group()
	subprocess.Popen("mplayer -prefer-ipv4 -fps 25 -frames 4 -vf pp=fd/ffmpegdeint -nosound -vo jpeg http://202.120.58.189:3054", shell=True, stdout=subprocess.PIPE)
	time.sleep(10)
	subprocess.Popen("mv 00000004.jpg /var/www/html/"+str(count)+".jpg", shell=True)
	indexfile.write(str(count*60)+ " " +str(count)+".jpg"+"\n")
	indexfile.flush()
	count += 1
	


a = raw_input("command >")

#os.kill(pVlc.pid,signal.SIGKILL)
#os.kill(pSource.pid,signal.SIGKILL)
#os.kill(pIndex.pid,signal.SIGKILL)
#os.kill(pLive.pid,signal.SIGKILL)
subprocess.Popen("rm tv*", shell=True)
